package org.lex.ftplist.ui.common;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import org.lex.ftplist.core.Index;
import org.lex.ftplist.ui.util.IndexUtils;
import org.lex.swing.TreeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CachedIndeiesPane extends JPanel {
	private JTree tree = null;
	private JPanel buttonsPane = null;
	private JButton okButton = null;
	private JButton cancelButton = null;
	private Logger log = LoggerFactory.getLogger(CachedIndeiesPane.class);

	public CachedIndeiesPane() {
		this.initComponents();
	}

	public Index getSelectedIndex() {
		TreePath path = tree.getSelectionPath();
		log.debug("select path=" + path);
		if (null == path) {
			return null;
		} else {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
			Object data = node.getUserObject();
			log.info("select node=" + data);
			if (data instanceof Index) {
				return (Index) data;
			} else {
				return null;
			}
		}
	}

	public JButton getOkButton() {
		return okButton;
	}

	public JButton getCancelButton() {
		return cancelButton;
	}

	private void initComponents() {
		this.setLayout(new BorderLayout(0, 5));
		this.add(new JScrollPane(getTree()), BorderLayout.CENTER);
		this.add(this.getButtonsPane(), BorderLayout.SOUTH);
	}

	private JTree getTree() {
		if (null == tree) {
			TreeNode root = IndexUtils.getIndexTree();
			tree = new JTree(root);
			tree.setRootVisible(false);
			tree.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			TreeUtils.expand(tree);
		}
		return tree;
	}

	private JPanel getButtonsPane() {
		if (null == buttonsPane) {
			FlowLayout l = new FlowLayout(FlowLayout.RIGHT);
			l.setAlignOnBaseline(true);
			buttonsPane = new JPanel(l);

			okButton = new JButton("OK");
			cancelButton = new JButton("Cancel");
			buttonsPane.add(okButton);
			buttonsPane.add(cancelButton);
		}
		return buttonsPane;
	}
}
